import React, { Component, useState, useEffect } from 'react';
import {
  StyleSheet,Animated,Clipboard,Alert,Vibration,Dimensions,Platform,
  NativeEventEmitter, NativeModules,DeviceEventEmitter
} from 'react-native';
import { Container, Content, View, Button, Text, Toast } from 'native-base';
import { connect } from 'react-redux';
import { Header } from '../../component';
import { RNCamera } from 'react-native-camera';

const height = Dimensions.get('window').height;
const width = Dimensions.get('window').width;

class Scanning extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      fadeAnim: new Animated.Value(0) 
    }
  }

  componentDidMount() {
    this.setState({
      show: true
    })
    this.startAnimation();
  }

  componentWillUnmount() {
    this.setState({
      show: false
    })
  }

  startAnimation(){
    this.state.fadeAnim.setValue(0);
    Animated.timing(                  // 随时间变化而执行动画
      this.state.fadeAnim,                       // 动画中的变量值
      {
        useNativeDriver: true,
        toValue: height,                   // 透明度最终变为1，即完全不透明
        duration: 3000,              // 让动画持续一段时间
      }
    ).start(()=>this.startAnimation()); 
  }

  // 点击复制
  clipboardFunc(str){
    str = str + '';
    Clipboard.setString(str);
    Toast.show({
      text: '文本已复制!',
      type: "success"
    })
  }

  // 结果反馈
  barcodeReceived(e) {
    if (this.state.show) {
      this.setState({
        show: false
      })
      if (e) {
        Vibration.vibrate([0, 500], false);
        let result = e.data;

        DeviceEventEmitter.emit("rigisterScan", {scanningVal: result});
        this.props.navigation.goBack()
        // Alert.alert(
        //   '扫描成功',
        //   '扫描结果：' + result,
        //   [
        //     {
        //       text: '确定', onPress: () => {
        //         this.setState({
        //           show: true
        //         })
        //         this.clipboardFunc(result);
        //       }
        //     },
        //     {
        //       text: '打开', onPress: () => {
        //         Clipboard.setString(result);
        //         this.props.navigation.navigate('OpenLink');
        //       }
        //     }
        //   ],
        //   { cancelable: false }
        // )
      } else {
        Alert.alert(
          '提示',
          '扫描失败，请将手机对准二维码重新尝试',
          [
            {
              text: '确定', onPress: () => {
                this.setState({
                  show: true
                })
              }
            }
          ],
          { cancelable: false }
        )
      }
    }
  }

  render() {
    let scanView = null;
    if (Platform.OS === 'ios') {
      scanView = (
        <RNCamera
          style={Styles.preview}
          type={RNCamera.Constants.Type.back}
          barCodeTypes={[RNCamera.Constants.BarCodeType.qr]}
          flashMode={RNCamera.Constants.FlashMode.auto}
          onBarCodeRead={(e) => this.barcodeReceived(e)}
        >
          <View style={Styles.cameraBody}>

          </View>
        </RNCamera>
      )
    } else {
      scanView = (
        <RNCamera
          style={Styles.preview}
          type={RNCamera.Constants.Type.back}
          googleVisionBarcodeType={RNCamera.Constants.GoogleVisionBarcodeDetection.BarcodeType.QR_CODE}
          flashMode={RNCamera.Constants.FlashMode.auto}
          onBarCodeRead={(e) => this.barcodeReceived(e)}
        >
          <View style={Styles.cameraBody}>
            <Animated.View
              style={{
                height: 2,
                backgroundColor: '#8e8df2',
                // marginTop: this.state.fadeAnim
              }}
            >
            </Animated.View>
          </View>
        </RNCamera>
      )
    }
    return (
      <Container>
        <Header title="扫描二维码" onLeftPress={() => this.props.navigation.goBack()} />
        <Content>
          {scanView}
        </Content>
      </Container>
    );
  }

}

const mapStateToProps = state => ({
  scanningType: state.global.scanningType,
});

const mapDispatchToProps = dispatch => ({
  setGlobalInfo: globalInfo => dispatch({ type: 'SET_GLOBALINFO', payload: { globalInfo } }),
});
export default connect(mapStateToProps, mapDispatchToProps)(Scanning);

const Styles = StyleSheet.create({
  preview: {
    flex: 1,
    width: width,
    height: height
  },
  cameraBody: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.2)'
  }
});
